package taskq

import "github.com/go-redis/redis/v8"

/**
* Author: dinglin
* Date: 2022/3/24 11:35 上午
 */

//stream_key task_id | task_name task_arg
var addStreamAndSetStreamIDScript = redis.NewScript(`
	local stream_key = KEYS[1]
	local task_id = KEYS[2]
	local task_name = ARGV[1]
	local task_arg = ARGV[2]
	local stream_id = redis.call('XADD', stream_key, '*', 'task_id', task_id)
	redis.call('HSET', task_id, 'name', task_name, 'arg', task_arg, 'stream_id', stream_id)
	return 'OK'
`)

//stream_key, task_id, zset_key |
var cancelTaskScript = redis.NewScript(`
	local stream_key = KEYS[1]
	local task_id = KEYS[2]
	local zset_key = KEYS[3]
	local stream_id = redis.call('HGET', task_id, 'stream_id')
	if not stream_id then
		redis.call('XDEL', stream_key, stream_id)
	end
	redis.call('ZREM', zset_key, task_id)
	redis.call('DEL', task_id)
	return 'OK'
`)

//zset_key, stream_key, task_id | now, count
var scheduleScript = redis.NewScript(`
	local zset_key = KEYS[1]
	local stream_key = KEYS[2]
	local task_id = KEYS[3]
	local now = ARGV[1]
	local count = ARGV[2]
	local task_ids = redis.call('ZRANGEBYSCORE', zset_key, '-inf', now, 'limit', 0, count)
	if not members then
		for index, task_id in ipairs(task_ids) do
			local stream_id = redis.call('XADD', stream_key, '*', 'task_id', task_id)
			redis.call('HSET', task_id, 'stream_id', stream_id)
			redis.call('ZREM', zset_key, member)
		end
	end
	return 'OK'
`)
